package cn.signalpha.modules.queue.runner;


import cn.signalpha.core.tool.utils.SpringUtil;
import cn.signalpha.modules.queue.enums.RedisDelayQueueEnum;
import cn.signalpha.modules.queue.handle.RedisDelayQueueHandle;
import cn.signalpha.modules.queue.utils.RedisDelayQueueUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 启动延迟队列 （如果是微服务，避免被其他服务消费，应该把此RUNNER和ENUM提取到其他相关delay的上一级）
 */
@Slf4j
@Component
@AllArgsConstructor
public class RedisDelayQueueRunner implements CommandLineRunner {

	private final RedisDelayQueueUtil redisDelayQueueUtil;

	@Override
	public void run(String... args) {
		RedisDelayQueueEnum[] queueEnums = RedisDelayQueueEnum.values();
		for (RedisDelayQueueEnum queueEnum : queueEnums) {
			new Thread(() -> {
				while (true) {
					try {
						Object take = redisDelayQueueUtil.getDelayQueue(queueEnum.getCode());
						if(take != null) {
							RedisDelayQueueHandle redisDelayQueueHandle = SpringUtil.getBean(queueEnum.getBeanId());
							redisDelayQueueHandle.execute(take);
						}
					} catch (InterruptedException e) {
						log.error("(Redis延迟队列异常中断) {}", e.getMessage());
					} catch (Exception e) {
						log.error("(Redis延迟队列处理异常) {}", e.getMessage(), e);
					}
				}
			}).start();
		}
		log.info("Redis延迟队列启动成功");
	}

}
